<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <div class="filter-container">
      <div class="search-container">
        <div class="search-item">
          <span class="search-title">员工名称</span>
          <el-input size="small" v-model="name" placeholder="请输入员工名称" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
          <span class="search-title">手机号码</span>
          <el-input size="small" v-model="phone" placeholder="请输入员工名称" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      <div class="right-container">
        <el-button v-if="canAddEmployee" type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">新增员工</el-button>
      </div>
    </div>

    <!-- 数据区域 -->
    <el-table :data="employees" style="width: 100%;" height="700">
      <el-table-column align="center" label="用户名" width="150">
        <template slot-scope="scope">
          <div class="user-info">
            <img
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              class="user-avatar"
            />
            <el-avatar
              v-else
              :size="30"
              style="margin-right:8px;"
              icon="el-icon-user-solid"
            ></el-avatar>
            <span class="username">{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="密码" width="120">
        <template slot-scope="scope">
          <div class="password-info">
            <span
              :class="['password-text', scope.row.showPassword ? 'visible' : 'hidden']"
            >
              {{ scope.row.showPassword ? '123456' : '******' }}
            </span>
            <el-button
              type="text"
              size="mini"
              @click="togglePassword(scope.row)"
              class="toggle-btn"
              :title="scope.row.showPassword ? '隐藏密码' : '显示密码'"
            >
              <i :class="scope.row.showPassword ? 'el-icon-hide' : 'el-icon-view'"></i>
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="员工姓名"></el-table-column>
      <el-table-column prop="gender" align="center" label="性别"></el-table-column>
      <el-table-column label="角色" align="center">
        <template slot-scope="scope">
          <span>{{ getRoleText(scope.row.role) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="salary" label="薪资" align="center"></el-table-column>
      <el-table-column prop="hireDate" label="入职日期" align="center"></el-table-column>
      <el-table-column prop="createdTime" label="创建时间" align="center"></el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template slot-scope="scope">
          <el-button v-if="canEditEmployee" size="mini" type="text" @click="handleEdit(scope.row)">
            <i class="el-icon-edit" style="margin-right: -3px;"></i>
            编辑
          </el-button>
          <el-button
            v-if="canDeleteEmployee"
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleDelete(scope.row)"
          >
            <i class="el-icon-delete" style="margin-right: -3px;"></i>
            删除
          </el-button>
          <el-dropdown v-if="canResetPassword" size="mini">
            <el-button size="small" type="text">
              <i class="el-icon-d-arrow-right" style="margin-right: -5px;"></i>
              更多
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-key" @click.native="handleResetPassword(scope.row)">重置密码</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        class="addDialog"
        :rules="rules"
        ref="formRef"
        size="small"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="formData.password" type="password" placeholder="请输入登录密码"></el-input>
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input v-model="formData.salary"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="formData.role">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="coach">教练</el-radio>
            <el-radio label="staff">前台</el-radio>
            <el-radio label="member">会员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="formData.hireDate"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="300px">
      <template #content>
        <p>确定要删除员工 {{ deleteEmployeeName }} 吗？</p>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" :visible.sync="resetPasswordDialogVisible" width="400px">
      <el-form :model="resetPasswordForm" :rules="resetPasswordRules" ref="resetPasswordFormRef" label-width="100px">
        <el-form-item label="员工姓名">
          <el-input v-model="resetPasswordForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmResetPassword">确认重置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script>
import { queryEmployees, saveEmployee, updateEmployee, deleteEmployee, resetEmployeePassword } from "@/api/user";
import { isAdmin, getCurrentUserRole } from '@/utils/permission';
import { deleteFile } from "@/api/common";
export default {
  data() {
    return {
      uploadHeaders:{
        'X-Requested-With': 'XMLHttpRequest',
        'token': localStorage.getItem('token') || '',
      },
      uploadUrl: "/api/admin/common/upload",
      // 员工数据
      employees: [],

      // 搜索筛选
      name: "",
      phone: "",

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 对话框
      dialogVisible: false,
      dialogType: "add", // 'add' 或 'edit'
      dialogTitle: "添加员工",
      formData: {
        name: "", // 员工姓名
        username: "", // 用户名
        password: "", // 密码
        gender: "", // 性别
        role: "", // 角色
        phone: "", // 手机号
        salary: "", // 薪资
        avatar: "", // 头像
        hireDate: "" // 入职日期
      },

      // 表单验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
        ],
        salary: [{ required: true, message: "请输入薪资", trigger: "blur" }],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        hireDate: [
          { required: true, message: "请选择入职日期", trigger: "change" }
        ]
      },

      // 删除相关
      deleteDialogVisible: false,
      deleteEmployeeId: "",
      deleteEmployeeName: "",

      // 重置密码相关
      resetPasswordDialogVisible: false,
      resetPasswordForm: {
        id: "",
        name: "",
        newPassword: "",
        confirmPassword: ""
      },
      resetPasswordRules: {
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: this.validateConfirmPassword, trigger: "blur" }
        ]
      }
    };
  },

  computed: {
    // 权限控制
    canManageEmployees() {
      return isAdmin(); // 只有管理员可以管理员工
    },
    canAddEmployee() {
      return isAdmin();
    },
    canEditEmployee() {
      return isAdmin();
    },
    canDeleteEmployee() {
      return isAdmin();
    },
    canResetPassword() {
      return isAdmin();
    },
    currentUserRole() {
      return getCurrentUserRole();
    }
  },

  methods: {
    // 角色文本转换
    getRoleText(role) {
      const roleMap = {
        'admin': '管理员',
        'coach': '教练',
        'staff': '前台',
        'member': '会员'
      };
      return roleMap[role] || role;
    },

    // 切换密码显示/隐藏
    togglePassword(row) {
      this.$set(row, 'showPassword', !row.showPassword);
    },

    handleAvatarSuccess(res) {
      // 上传成功，需要在前端回显(对象属性更新，vue无法响应，使用vue的set方法)
      //const url = URL.createObjectURL(file.raw);
      this.$set(this.formData, "avatar", res.data);
      // this.formData = {
      //   ...this.formData,
      //   avatar: url
      // };
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 验证确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.resetPasswordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    // 分页
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.handleSearch(); // 重新搜索以应用新的页面大小
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.handleSearch(); // 重新搜索以应用新的页码
    },

    // 搜索
    handleSearch() {
      console.log('开始搜索员工数据...');
      // 发起请求到后端数据库
      queryEmployees({
        name: this.name,
        phone: this.phone,
        pageSize: this.pageSize,
        page: this.currentPage
      }).then(res => {
        console.log('员工数据API响应:', res);
        if (res.data.code === 1) {
          const data = res.data.data;
          this.employees = data.records || [];
          this.total = data.total || 0;
          console.log('从数据库加载员工数据成功:', this.employees);
        } else {
          this.$message.error(res.data.msg || '获取员工数据失败');
          this.employees = [];
          this.total = 0;
        }
      }).catch(error => {
        console.error('员工数据API调用失败:', error);
        this.$message.error('网络错误，无法获取员工数据');
        this.employees = [];
        this.total = 0;
      });
    },



    // 添加员工
    handleAdd() {
      this.dialogType = "add";
      this.dialogTitle = "添加员工";
      // 重置表单数据
      this.formData = {
        name: "",
        username: "",
        password: "",
        gender: "",
        role: "",
        phone: "",
        salary: "",
        avatar: "",
        hireDate: ""
      };
      this.dialogVisible = true;
    },

    // 编辑员工
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogTitle = "编辑员工";
      this.formData = { ...row }; // 复制对象，避免直接修改原数据
      this.dialogVisible = true;
    },

    // 保存员工信息
    handleSave() {
      // 调用表单的验证方法
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.dialogType === "add") {
            // 添加新员工到数据库
            console.log("添加员工数据:", this.formData);

            saveEmployee(this.formData).then((res)=>{
              if(res.data.code===1){
                this.$message.success("添加成功");
                this.dialogVisible = false;
                // 重新从数据库加载员工列表
                this.handleSearch();
              }else{
                this.$message.error(res.data.msg || '添加员工失败');
              }
            }).catch((error) => {
              console.error("添加员工API调用失败:", error);
              this.$message.error('网络错误，添加员工失败');
            });
          } else {
            // 编辑员工 - 调用更新API
            console.log("编辑员工数据:", this.formData);

            updateEmployee(this.formData).then((res)=>{
              if(res.data.code===1){
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.handleSearch();
              }else{
                this.$message.error(res.data.msg || '修改员工失败');
              }
            }).catch((error) => {
              console.error("修改员工API调用失败:", error);
              this.$message.error('网络错误，修改员工失败');
            });
          }
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },

    // 关闭对话框
    handleClose(done) {
      // 如果添加头像了，需要删除
      if (this.formData.avatar) {
        deleteFile(this.formData.avatar)
      }
      // 表单数据重置
      this.$refs.formRef.resetFields();
      done();
    },

    // 删除员工
    handleDelete(row) {
      this.deleteEmployeeId = row.staffId;
      this.deleteEmployeeName = row.name;
      this.deleteDialogVisible = true;
    },

    // 确认删除
    handleConfirmDelete() {
      console.log("删除员工ID:", this.deleteEmployeeId);

      deleteEmployee(this.deleteEmployeeId).then((res)=>{
        if(res.data.code===1){
          this.$message.success("删除成功");
          this.deleteDialogVisible = false;
          this.handleSearch(); // 重新从数据库加载数据
        }else{
          this.$message.error(res.data.msg || '删除员工失败');
        }
      }).catch((error) => {
        console.error("删除员工API调用失败:", error);
        this.$message.error('网络错误，删除员工失败');
      });
    },

    // 重置密码
    handleResetPassword(row) {
      this.resetPasswordForm = {
        id: row.staffId,
        name: row.name,
        newPassword: "",
        confirmPassword: ""
      };
      this.resetPasswordDialogVisible = true;
    },

    // 确认重置密码
    handleConfirmResetPassword() {
      this.$refs.resetPasswordFormRef.validate(valid => {
        if (valid) {
          console.log("重置密码:", this.resetPasswordForm);

          resetEmployeePassword({
            id: this.resetPasswordForm.id,
            newPassword: this.resetPasswordForm.newPassword
          }).then((res)=>{
            if(res.data.code===1){
              this.$message.success("密码重置成功");
              this.resetPasswordDialogVisible = false;
            }else{
              this.$message.error(res.data.msg || '密码重置失败');
            }
          }).catch((error) => {
            console.error("重置密码API调用失败:", error);
            this.$message.error('网络错误，密码重置失败');
          });
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    }
  },
  mounted() {
    //初始化表格数据
    this.handleSearch();
  }
};
</script>
  
<style lang="less" scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 10px;
  .search-container {
    display: flex;
    .search-item {
      margin-right: 10px;
      .search-title {
        line-height: 32px;
        padding: 0 12px 0 0;
        color: #606266;
        font-size: 14px;
        font-weight: 700;
      }
    }
  }
}
.addDialog /deep/ .el-input {
  width: 280px;
}
.addDialog {
  .avatar-uploader::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader::v-deep .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
}

// 用户名列样式
.user-info {
  display: flex;
  align-items: center;
  justify-content: center;

  .user-avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 8px;
    object-fit: cover;
  }

  .username {
    font-weight: 500;
    color: #303133;
  }
}

// 密码列样式
.password-info {
  display: flex;
  align-items: center;
  justify-content: center;

  .password-text {
    font-family: 'Courier New', monospace;
    margin-right: 5px;

    &.hidden {
      color: #909399;
    }

    &.visible {
      color: #409EFF;
      font-weight: 500;
    }
  }

  .toggle-btn {
    padding: 0;
    margin-left: 5px;
    color: #606266;

    &:hover {
      color: #409EFF;
    }
  }
}
</style>